import express from "express";
import mysql from "mysql2/promise";
import * as dbConfig from "../config/db-config.js";
import { migrateTableTransaction } from "../services/migrate-transaction-service.js";

const router = express.Router();

router.post("/", async (req, res) => {
  const { tableName, removeField = false } = req.body;
  if (!tableName) {
    return res.status(400).json({ success: false, message: "缺少 tableName 参数" });
  }

  let sourceConn, targetConn;
  try {
    const config = await dbConfig.loadConfig();
    sourceConn = await mysql.createConnection(config.source);
    targetConn = await mysql.createConnection(config.target);

    const result = await migrateTableTransaction(sourceConn, targetConn, tableName, removeField);
    res.json(result);
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  } finally {
    if (sourceConn) await sourceConn.end();
    if (targetConn) await targetConn.end();
  }
});

export default router;
